<?php
/**
 * @Created by PhpStorm.
 * @Name 订单控制器
 * @User: djh/Wong
 * @Date: 2016/11/7
 * @Copyright : MPE.Fiidee.Monda.Cn
 */

namespace member\action;
use herosphp\http\HttpRequest;
use herosphp\utils\AjaxResult;
use herosphp\bean\Beans;
use herosphp\core\Loader;

class OrderAction extends CommonAction{

    protected $member_id=null;
    protected $dasu_id=null;
    protected $serviceBean="trading.tradingOrder.service";

    public function __construct(){
        parent::__construct();
        $this->member_id = $this->_user->__get('id');
        $this->dasu_id = $this -> _user -> __get('dasu_pay_id');
    }

    /**
     * 订单列表
     * @param HttpRequest $request
     */
    public function index(HttpRequest $request){
        $orderService = Beans::get($this->getServiceBean());
        $OrderModel = Loader::model('tradingOrder');
        $order_status = $request->getParameter('order_status');
        $type = $request->getParameter('type');
        $page = $request->getParameter('page');
        if($page<=0) $page = 1;
        $this->setPage($page);
        if($type == 1){
            $pagesize = 5;
        }else{
            $pagesize = 8;
        }
        $this->setPagesize($pagesize);
        $member_id = $this->member_id;
        $conditions = array();
        $conditions['member_id'] = $member_id;
        if($order_status != 'all' && $order_status != ''){
            $conditions['order_status'] = $order_status;
        }
        $items = $orderService->getOrderList($conditions,$pagesize,$page);
        $item = $items['items'];

        foreach ($item as $k => $v) {

            $item[$k]['payway'] = $orderService->getPaywayText($v['pay_way']);
            $item[$k]['shippingway'] = $orderService->getShippingwayText($v['shipping_way']);
            $item[$k]['orderstatus'] = $orderService->getPaystatusText($v['order_status']);

        }
        //总数
        $total = $orderService->count(array('member_id'=>$member_id));
        //待卖家确认总量
        $merchant_confirmTotal = $orderService->count(array('member_id'=>$member_id,'order_status'=>$OrderModel::WAIT_FOR_MERCHANT_CONFIRMATION));
        //待买家确认总量
        $user_confirmTotal = $orderService->count(array('member_id'=>$member_id,'order_status'=>$OrderModel::WAIT_FOR_USER_CONFIRMATION));
        //待支付总量
        $noPayTotal = $orderService->count(array('member_id'=>$member_id,'order_status'=>$OrderModel::ORDER_STATUS_UNPAY));
        //代发货总量
        $noShippedTotal = $orderService->count(array('member_id'=>$member_id,'order_status'=>$OrderModel::ORDER_STATUS_TO_BE_SHIPPED));
        //已发货总量
        $shippedTotal = $orderService->count(array('member_id'=>$member_id,'order_status'=>$OrderModel::ORDER_STATUS_SHIPPED));
        //已取消总量
        $cancelTotal = $orderService->count(array('member_id'=>$member_id,'order_status'=>$OrderModel::ORDER_STATUS_CANCELED));
        //已完成总量
        $completeTotal = $orderService->count(array('member_id'=>$member_id,'order_status'=>$OrderModel::ORDER_STATUS_COMPLETED));

        $this->memberPagemenu($items['total']);
        $this->assign('items', $item);
        $this->assign('total', $total);
        $this->assign('merchant_confirmTotal', "$merchant_confirmTotal");
        $this->assign('user_confirmTotal', "$user_confirmTotal");
        $this->assign('noPayTotal', "$noPayTotal");
        $this->assign('noShippedTotal', $noShippedTotal);
        $this->assign('shippedTotal', $shippedTotal);
        $this->assign('cancelTotal', $cancelTotal);
        $this->assign('completeTotal', $completeTotal);
        $this->assign('SHIPPING_WAY_BUYER', $OrderModel::SHIPPING_WAY_BUYER);
        $this->assign('PAY_WAY_ONLINE', $OrderModel::PAY_WAY_ONLINE);
        $this->assign('WAIT_FOR_MERCHANT_CONFIRMATION', $OrderModel::WAIT_FOR_MERCHANT_CONFIRMATION);
        $this->assign('WAIT_FOR_USER_CONFIRMATION', $OrderModel::WAIT_FOR_USER_CONFIRMATION);
        $this->assign('ORDER_STATUS_UNPAY', $OrderModel::ORDER_STATUS_UNPAY);
        $this->assign('ORDER_STATUS_TO_BE_SHIPPED', $OrderModel::ORDER_STATUS_TO_BE_SHIPPED);
        $this->assign('ORDER_STATUS_SHIPPED', $OrderModel::ORDER_STATUS_SHIPPED);
        $this->assign('ORDER_STATUS_COMPLETED', $OrderModel::ORDER_STATUS_COMPLETED);
        $this->assign('ORDER_STATUS_CANCELED', $OrderModel::ORDER_STATUS_CANCELED);
        $this->assign('order_status', $order_status);
        $requestType = $request->getParameter('ajax');
        if($requestType) {
            $this->setView('/order/order_index_page');
        }else {
            $this->setView('/order/order_index');
        }
    }

    /**
     * 订单详情
     * @param HttpRequest $request
     */
    public function detail(HttpRequest $request){
        $orderService = Beans::get($this->getServiceBean());
        $OrderModel = Loader::model('tradingOrder');
        $id = $request->getParameter('id');
        $no = $request->getParameter('no');
        $post = $request->getParameter('post');
        $item = $orderService->getDetail($id,$no,$this->member_id);
        if(!$item){
            return $this->message('没有此订单','/member/index');
        }
        if($item == 'denied'){
            return $this->message('您无权限查看此订单','/member/index');
        }
        if($post && $post['buyers_remark'] != ''){//更新买家备注
            $orderService->updates(array('buyers_remark'=>$post['buyers_remark']),array('id'=>$id,'app_id'=>appId()));
        }
        $item['payway'] = $orderService->getPaywayText($item['pay_way']);
        $item['shippingway'] = $orderService->getShippingwayText($item['shipping_way']);
        $item['step'] = $item['order_status']>=3?$item['order_status']-3:0;
        $this->assign('item',$item);
        $this->assign('PAY_WAY_OFFLINE', $OrderModel::PAY_WAY_OFFLINE);
        $this->assign('ORDER_STATUS_UNPAY', $OrderModel::ORDER_STATUS_UNPAY);
        $this->assign('ORDER_PENDING_RECEIPT', $OrderModel::ORDER_PENDING_RECEIPT);
        $this->assign('ORDER_STATUS_TO_BE_SHIPPED', $OrderModel::ORDER_STATUS_TO_BE_SHIPPED);
        $this->assign('ORDER_STATUS_SHIPPED', $OrderModel::ORDER_STATUS_SHIPPED);
        $this->assign('ORDER_STATUS_COMPLETED', $OrderModel::ORDER_STATUS_COMPLETED);
        $this->assign('ORDER_STATUS_CANCELED', $OrderModel::ORDER_STATUS_CANCELED);
        $this->assign('SHIPPING_WAY_SELLER', $OrderModel::SHIPPING_WAY_SELLER);
        $this->assign('SHIPPING_WAY_BUYER', $OrderModel::SHIPPING_WAY_BUYER);
        $this -> setView('/order/order_detail');
    }

    /**
     * 购物车
     * @param HttpRequest $request
     */
    public function cart(HttpRequest $request){
        $cartService = Beans::get('trading.tradingCart.service');
        $item = array();
        if($this->_user->hasLogin()){
            $member_id = $this->_user->__get('id');
            $item = $cartService->getCarts($member_id);
            $this->assign('username' , $this->_user->__get('username'));
        }else{
            $productIdArr = json_decode($_COOKIE['cartInfo']);
            if(is_array($productIdArr)){
                $item = $cartService->getCookieProduct($productIdArr);
            }
        }
        $this->assign('item',$item);
        $this -> setView('/order/order_cart');
    }

    /**
     * 获取购物车信息
     */
    public function getCart(){
        $cartService = Beans::get('trading.tradingCart.service');
        $item = array();
        $member_id = $this->_user->__get('id');
        if($member_id){
            $item = $cartService->getCarts($member_id);
            AjaxResult::ajaxResult(AjaxResult::OP_SUCCESS,'success',$item);
        }else{
            $productIdArr = json_decode($_COOKIE['cartInfo']);
            if(is_array($productIdArr)){
                $item = $cartService->getCookieProduct($productIdArr);
                AjaxResult::ajaxResult(AjaxResult::OP_SUCCESS,'success',$item);
            }
            AjaxResult::ajaxResult(AjaxResult::OP_SUCCESS,'success',array('product'=>array()));
        }
    }

    /**
     * 删除购物车商品
     * @param HttpRequest $request
     */
    public function delCartProduct(HttpRequest $request){
        $cartService = Beans::get('trading.tradingCart.service');
        $id = $request->getParameter('id');
        if($this->_user->hasLogin()){
            $member_id = $this->member_id;
            $result = $cartService->delCartProduct($member_id,$id);
        }else{
            $result = true;
        }
        if($result){
            $cartInfo = json_decode($_COOKIE['cartInfo']);
            $key = array_search($id,$cartInfo);
            if($key !== false){
                array_splice($cartInfo,$key,1);
            }
            setCookie('cartInfo',json_encode($cartInfo),time()+3600*24*365,'/');
        }

        if($result){
            AjaxResult::ajaxSuccessResult();
        }else{
            AjaxResult::ajaxFailtureResult();
        }
    }

    /**
     * 购物车结算
     * @param HttpRequest $request
     */
    public function createOrder(HttpRequest $request){
        $cartService = Beans::get('trading.tradingCart.service');
        $ids = $request->getParameter('id');
        $quantity = $request->getParameter('quantity');
        $isCart = $request->getParameter('isCart');
        if(!$ids || !$quantity){
            return $this->message('没有选择产品','/member/order/cart');

        }
        $member_id = $this->member_id;
        $item = $cartService->createOrder($member_id,$ids,$quantity);

        if($item == -1){//产品不在同一个交收仓
            return $this->message('产品不在同一个交收仓','/member/order/cart');
        }
        if($item == -2){//产品不是同一种交收方式
            return $this->message('产品不是同一种交收方式','/member/order/cart');
        }
        if($item == -3){//购买数量不合法
            return $this->message('产品数据有误','/member/order/cart');
        }
        if($item == -4){//购买数量不合法
            return $this->message('购买数量不合法','/member/order/cart');
        }
        $signInfo = $this->_user->getSignInfo();
        $sign_status = true;
        if($signInfo['sign_status'] != 1){//用户没有签约 不允许使用大塑支付
            $sign_status = false;
        }

        $productModel = Loader::model('product');
        $addresstModel = Loader::model('memberReceiptAddress');
        $addressService = Beans::get('member.receiptAddress.service');
        $items = $addressService->getItems(array('member_id'=>$member_id,'add_type'=>$addresstModel::ADD_TYPE_USER));

        $this->assign('address_item',$items);
        $this->assign('SHIPPING_WAY_BUYER',$productModel::SHIPPING_WAY_BUYER);
        $this->assign('DEFAULT_TYPE_IS',$addresstModel::DEFAULT_TYPE_IS);
        $this->assign('sign_status',$sign_status);
        $this->assign('item',$item);
        $this->assign('ids',json_encode($ids));
        $this->assign('quantity',json_encode($quantity));
        $this->assign('isCart',$isCart?$isCart:0);
        $this -> setView('/order/order_createOrder');
    }

    /**
     * 生成订单
     * @param HttpRequest $request
     */
    public function addOrder(HttpRequest $request){
        $orderModel = Loader::model('tradingOrder');
        $product = $request->getParameter('product');
        $data = $request->getParameter('data');
        $data['shipping'] = $request->getParameter('shipping');
        $product['product_id'] = json_decode($product['product_id']);
        $product['product_quantity'] = json_decode($product['product_quantity']);
        $data['address']['id'] = $request->getParameter('address_id');
        $data['add_type'] = $orderModel::ADD_TYPE_USER;//用户添加的订单
        $data['member_id'] = $this->member_id;
        $data['product'] = $product;

        $settingService = Beans::get('admin.adminSetting.service');

        if($word=$settingService->hasDenyWord($data['buyers_remark'])){

            AjaxResult::ajaxResult('001','您的留言含有违禁词，请修改后再提交!"'.$word.'"');

        }

        $orderService = Beans::get('trading.tradingOrder.service');
        $res = $orderService->addOrder($data);
        if($res == -1){
            AjaxResult::ajaxResult('001','订单没有选择产品');
        }elseif($res == -2){
            AjaxResult::ajaxResult('001','超出库存');
        }elseif($res == -3){
            AjaxResult::ajaxResult('001','订单没有选择收货地址');
        }elseif($res == false){
            AjaxResult::ajaxResult('001','添加订单失败');
        }else{
            AjaxResult::ajaxResult('000','添加订单成功',$res);
        }
    }

    /**
     * 用户议价 todo 第二期
     * @param HttpRequest $request
     */
    public function userBargaining(HttpRequest $request){
        $id = $request->getParameter('id');
        $data = $request->getParameter('data');
        $member_id = $this->member_id;
        $service = Beans::get($this->getServiceBean());
        if(!$service->checkOrder($member_id)){
            AjaxResult::ajaxResult('001','您没有权限操作此订单');
        }
        $item = $service->userBargaining($id,$member_id,$data);
        if($item){
            AjaxResult::ajaxSuccessResult();
        }else{
            AjaxResult::ajaxFailtureResult();
        }
    }

    /**
     * 用户二次确认
     * @param HttpRequest $request
     */
    public function userSecondConfirmation(HttpRequest $request){
        $id = $request->getParameter('id');
        $member_id = $this->member_id;
        $service = Beans::get($this->getServiceBean());
        if(!$service->checkOrder($id,$member_id)){
            AjaxResult::ajaxResult('001','您没有权限操作此订单');
        }
        $item = $service->userSecondConfirmation($id,$member_id);
        if($item){
            AjaxResult::ajaxSuccessResult();
        }else{
            AjaxResult::ajaxFailtureResult();
        }
    }

    /**
     * 取消订单
     * @param HttpRequest $request
     */
    public function cancelOrder(HttpRequest $request){
        $id = $request->getParameter('id');
        $service = Beans::get($this->getServiceBean());
        if(!$service->checkOrder($id,$this->member_id)){
            AjaxResult::ajaxResult('001','您没有权限操作此订单');
        }
        $item = $service->cancelOrder($id,1);//用户取消订单
        if($item){
            AjaxResult::ajaxSuccessResult();
        }else{
            AjaxResult::ajaxFailtureResult();
        }
    }

    /**
     * 提货单
     * @param HttpRequest $request
     */
    public function billOfLading(HttpRequest $request){
        $service = Beans::get($this->getServiceBean());
        $id = $request->getParameter('id');
        if(!$service->checkOrder($id,$this->member_id)){
            return $this->message('您无权限查看此订单','/member/index');
        }
        $orderProductModel = Loader::model('tradingOrderProduct');
        $shippingModel = Loader::model('tradingOrderShipping');
        $ladingModel = Loader::model('tradingOrderLading');
        $item = $service->getItem($id);
        $shipping = $shippingModel->getItem(array('order_id'=>$id));
        $products = $orderProductModel->getItems(array('order_id'=>$id));
        foreach($products as $k=>$v){
            $attribute = json_decode($v['attribute'],true);
            $products[$k]['product_name'] = $attribute['product_name'];
            $products[$k]['factory_name'] = $attribute['factory_name'];
            $products[$k]['brand_name'] = $attribute['brand_name'];
            $products[$k]['pkg_size'] = $attribute['pkg_size'];
        }
        $kefu_arr = json_decode(C('cs_qq'),true);
        $qq = '';
        foreach($kefu_arr as $v){
            $qq .= $v['qq'].',';
        }
        $cs_qq = rtrim($qq,',');
        $site_name = C('site_name');
        $site_url = C('site_url');
        $cs_phone = C('cs_phone');
        $lading = $ladingModel->getItem(array('order_id'=>$id));
        $this->assign('item',$item);
        $this->assign('cs_qq',$cs_qq);
        $this->assign('site_name',$site_name);
        $this->assign('site_url',$site_url);
        $this->assign('cs_phone',$cs_phone);
        $this->assign('shipping',$shipping);
        $this->assign('products',$products);
        $this->assign('lading',$lading);
        $this->setView('/order/order_pick');

    }

    /**
     * 大塑支付页面
     * @param HttpRequest $request
     */
    public function dasuPayOrder(HttpRequest $request){
        $orderModel = Loader::model('tradingOrder');
        $id = $request->getParameter('id');
        $type = $request->getParameter('type');
        $service = Beans::get($this->getServiceBean());
        $item = $service->getDetail($id,null,$this->member_id);
        if(!$item){
            return $this->message('此订单信息有误','/member/order/index?order_status='.$orderModel::ORDER_STATUS_UNPAY);
        }
        if($item == 'denied'){
            return $this->message('您无权限查看此订单','/member/order/index?order_status='.$orderModel::ORDER_STATUS_UNPAY);
        }
        if($item['order_status'] > $orderModel::ORDER_STATUS_UNPAY){//订单已付款
            return $this->message('此订单不需要支付','/member/order/detail?id='.$id);
        }
        $order_mode = C('order_mode');
        if($order_mode != '' && $order_mode != 'DirectTrade' && $item['order_status'] < $orderModel::ORDER_STATUS_UNPAY){//不是直接交易 且状态未到待支付
            $message = $type==1?'':'此订单等待卖家确认';
            $url = '/member/order/index?order_status=' . $orderModel::WAIT_FOR_MERCHANT_CONFIRMATION;
            return $this->message($message,$url);
        }
        $live_time = C('order_life');
        $item['last_time'] = date('Y-m-d H:i:s',strtotime($item['order_time'])+$live_time*60);
        //var_dump($item);
        $this->assign('item',$item);
        $this->assign('id',$id);
        if($item['pay_way'] == $orderModel::PAY_WAY_OFFLINE){//线下支付
            //$this->setView('order/order_success');
            return $this->message('','/member/order/index');
        }else{
            if($_POST){
                $this->payOrder($request);
            }
            //可用余额
            $usable = $this->_user->__get('usable');
            $username = $this->_user->getSignInfo('username');
            $isEnough = $usable>=$item['actual_amount']?true:false;
            $this->assign('usable',$usable);
            $this->assign('username',$username);
            $this->assign('isEnough',$isEnough);
            $this->setView('order/order_dasuPay');
        }
    }

    /**
     * 交易
     * @param HttpRequest $request
     */
    public function payOrder(HttpRequest $request){
        $service = Beans::get($this->getServiceBean());
        $id = $request->getParameter('id');
        if(!$service->checkOrder($id,$this->member_id)){
            $this->assign('wrong','您没有权限支付此订单');
            return ;
        }
        $pwd = $request->getParameter('pwd','trim');
        $dasu_id = $this->dasu_id;

        if(passwd($pwd) != $this->_user->__get('tradepass')){
            $this->assign('wrong','交易密码错误');
            return ;

        }

        if(!$dasu_id){
            $this->assign('wrong','没有注册大塑账户');
            return ;
        }

        $signInfo = $this->_user->getSignInfo();
        if ($signInfo['sign_status'] == '0'){
            $this->assign('wrong','您还没没有签约');
            return ;
        }
        if ($signInfo['sign_status'] == '2'){
            $this->assign('wrong','您已经解约');
            return ;
        }

        $result = $service->payOrder($id,$dasu_id);
        if($result){
            $this->_user->updateSignInfo();//重新抓取saas数据
            //AjaxResult::ajaxResult('000','订单支付成功');
            header('Location:'.url('/member/order/successOrder?id='.$id).'?dir='.$_SERVER['HTTP_REFERER']);
        }else{
            $this->assign('wrong','订单支付失败');
            return ;
        }
    }

    /**
     * 支付成功页面
     * @param HttpRequest $request
     */
    public function successOrder(HttpRequest $request){
        $service = Beans::get($this->getServiceBean());
        $orderModel = Loader::model('tradingOrder');

        $id = $request->getParameter('id');

        $item = $service->getDetail($id,null,$this->member_id);
        if(!$item){
            return $this->message('没有此订单','/member/index');
        }
        if($item == 'denied'){
            return $this->message('您无权限查看此订单','/member/index');
        }
        //订单不为线上支付 或者 订单状态不为待发货
        if($item['pay_way'] != $orderModel::PAY_WAY_ONLINE || $item['order_status'] != $orderModel::ORDER_STATUS_TO_BE_SHIPPED){
            return $this->message('','/member/order/index?order_status='.$orderModel::ORDER_STATUS_TO_BE_SHIPPED);
        }
        $this->assign('PAY_WAY_ONLINE',$orderModel::PAY_WAY_ONLINE);
        $this->assign('SHIPPING_WAY_BUYER',$orderModel::SHIPPING_WAY_BUYER);
        $this->assign('item',$item);
        $this->assign('id',$id);
        $this -> setView('order/order_success');
    }

    /**
     * 校验交易密码
     * @param HttpRequest $request
     */
    public function checkPayPassword(HttpRequest $request){
        $pwd = $request->getParameter('pwd','trim');
        $__token = md5(getRandStr(6));
        $_SESSION['payToken'] = $__token;
        if(passwd($pwd) == $this->_user->__get('tradepass')){
            AjaxResult::ajaxResult('000','交易密码正确',array('token'=>$__token));

        }else{
            AjaxResult::ajaxResult('001','交易密码错误');
        }
    }

    /**
     * 确认收货
     * @param HttpRequest $request
     */
    public function confirmDelivery(HttpRequest $request){
        $id = $request->getParameter('id');
        $service = Beans::get($this->getServiceBean());
        if(!$service->checkOrder($id,$this->member_id)){
            AjaxResult::ajaxResult('001','您没有权限操作此订单');
        }
        $dasu_id = $this->dasu_id;
        $item = $service->confirmDelivery($id,$dasu_id);
        if($item){
            $this->_user->updateSignInfo();//重新抓取saas数据
            AjaxResult::ajaxSuccessResult();
        }else{
            AjaxResult::ajaxFailtureResult();
        }
    }
}